<template>
  <div class="purchase-prediction-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2>购买预测分析</h2>
        <p>基于用户行为数据预测购买时间、金额和产品偏好，提供精准的营销策略</p>
      </div>
      <div class="header-actions">
        <el-button :icon="Refresh" @click="() => refreshData(true)">刷新数据</el-button>
        <el-button type="primary" :icon="MagicStick" @click="runPrediction" :loading="predicting">
          执行预测
        </el-button>
        <el-button :icon="Download" @click="exportResults">导出结果</el-button>
      </div>
    </div>

    <!-- 预测概览 -->
    <div class="overview-section">
      <el-row :gutter="24">
        <el-col :xs="12" :sm="6">
          <div class="metric-card purchase-intent">
            <div class="metric-icon">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="metric-content">
              <h3>{{ overviewData.highIntentUsers }}</h3>
              <p>高购买意向用户</p>
              <span class="metric-change success">+{{ overviewData.intentChange }}%</span>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="metric-card predicted-revenue">
            <div class="metric-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="metric-content">
              <h3>¥{{ overviewData.predictedRevenue.toLocaleString() }}</h3>
              <p>预测收入</p>
              <span class="metric-change success">+{{ overviewData.revenueChange }}%</span>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="metric-card avg-order-value">
            <div class="metric-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="metric-content">
              <h3>¥{{ overviewData.avgOrderValue }}</h3>
              <p>预测平均订单</p>
              <span class="metric-change warning">+{{ overviewData.aovChange }}%</span>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="metric-card conversion-rate">
            <div class="metric-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="metric-content">
              <h3>{{ overviewData.conversionRate }}%</h3>
              <p>预测转化率</p>
              <span class="metric-change success">+{{ overviewData.conversionChange }}%</span>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 主要内容区域 -->
    <el-row :gutter="24">
      <!-- 左侧：购买时间预测和趋势 -->
      <el-col :xs="24" :lg="16">
        <!-- 购买时间分布 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>购买时间预测分布</h3>
              <div class="header-actions">
                <el-select v-model="timeRange" size="small" style="width: 120px">
                  <el-option label="未来7天" value="7d" />
                  <el-option label="未来30天" value="30d" />
                  <el-option label="未来90天" value="90d" />
                </el-select>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <LineChart
              :data="purchaseTimeChartData"
              :x-axis-data="purchaseTimeLabels"
              height="300px"
            />
          </div>
        </el-card>

        <!-- 购买金额预测 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>购买金额预测分布</h3>
              <div class="header-actions">
                <el-radio-group v-model="amountType" size="small">
                  <el-radio-button label="individual">个人</el-radio-button>
                  <el-radio-button label="segment">分群</el-radio-button>
                  <el-radio-button label="category">品类</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <PieChartComponent
              :data="purchaseAmountData"
              :options="amountChartOptions"
              height="360px"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：产品推荐和模型性能 -->
      <el-col :xs="24" :lg="8">
        <!-- 热门预测产品 -->
        <el-card class="product-recommendation-card">
          <template #header>
            <h3>热门预测产品</h3>
          </template>
          <div class="product-list">
            <div 
              v-for="product in topProducts" 
              :key="product.id"
              class="product-item"
            >
              <div class="product-info">
                <img :src="product.image" :alt="product.name" class="product-image" />
                <div class="product-details">
                  <h4>{{ product.name }}</h4>
                  <p class="product-category">{{ product.category }}</p>
                  <p class="product-price">¥{{ product.price }}</p>
                </div>
              </div>
              <div class="product-metrics">
                <div class="metric">
                  <span class="label">预测销量</span>
                  <span class="value">{{ product.predictedSales }}</span>
                </div>
                <div class="metric">
                  <span class="label">购买概率</span>
                  <span class="value">{{ product.probability }}%</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 预测准确性 -->
        <el-card class="accuracy-card">
          <template #header>
            <h3>预测准确性分析</h3>
          </template>
          <div class="accuracy-metrics">
            <div class="accuracy-item">
              <span class="accuracy-label">时间预测准确率</span>
              <div class="accuracy-value">
                <el-progress :percentage="accuracyData.timeAccuracy" :stroke-width="8" />
                <span class="percentage">{{ accuracyData.timeAccuracy }}%</span>
              </div>
            </div>
            <div class="accuracy-item">
              <span class="accuracy-label">金额预测准确率</span>
              <div class="accuracy-value">
                <el-progress :percentage="accuracyData.amountAccuracy" :stroke-width="8" />
                <span class="percentage">{{ accuracyData.amountAccuracy }}%</span>
              </div>
            </div>
            <div class="accuracy-item">
              <span class="accuracy-label">产品预测准确率</span>
              <div class="accuracy-value">
                <el-progress :percentage="accuracyData.productAccuracy" :stroke-width="8" />
                <span class="percentage">{{ accuracyData.productAccuracy }}%</span>
              </div>
            </div>
            <div class="accuracy-item">
              <span class="accuracy-label">整体预测准确率</span>
              <div class="accuracy-value">
                <el-progress :percentage="accuracyData.overallAccuracy" :stroke-width="8" />
                <span class="percentage">{{ accuracyData.overallAccuracy }}%</span>
              </div>
            </div>
          </div>
          <div class="model-info">
            <p><strong>模型版本:</strong> {{ accuracyData.version }}</p>
            <p><strong>训练数据:</strong> {{ accuracyData.trainingSamples }} 条</p>
            <p><strong>更新时间:</strong> {{ accuracyData.lastUpdate }}</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户购买预测列表 -->
    <el-card class="prediction-list-card">
      <template #header>
        <div class="card-header">
          <h3>用户购买预测列表</h3>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户ID或姓名"
              :prefix-icon="Search"
              style="width: 200px; margin-right: 12px;"
              clearable
            />
            <el-select v-model="intentFilter" placeholder="购买意向" style="width: 120px; margin-right: 12px;">
              <el-option label="全部" value="" />
              <el-option label="高意向" value="High" />
              <el-option label="中意向" value="Medium" />
              <el-option label="低意向" value="Low" />
            </el-select>
            <el-select v-model="categoryFilter" placeholder="产品类别" style="width: 120px;">
              <el-option label="全部" value="" />
              <el-option label="电子产品" value="electronics" />
              <el-option label="服装" value="clothing" />
              <el-option label="家居" value="home" />
              <el-option label="美妆" value="beauty" />
            </el-select>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="filteredPredictions" 
        v-loading="loading"
        stripe
        @sort-change="handleSortChange"
      >
        <el-table-column prop="userId" label="用户ID" min-width="100" />
        <el-table-column prop="userName" label="用户姓名" min-width="120" />
        <el-table-column prop="purchaseProbability" label="购买概率" min-width="150" sortable>
          <template #default="{ row }">
            <el-progress
              :percentage="Math.round(row.purchaseProbability * 100)"
              :stroke-width="8"
              :color="getIntentColor(row.intentLevel)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="intentLevel" label="购买意向" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getIntentTagType(row.intentLevel)">
              {{ getIntentLevelText(row.intentLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="predictedDate" label="预测购买时间" min-width="140" />
        <el-table-column prop="predictedAmount" label="预测金额" min-width="120" sortable>
          <template #default="{ row }">
            ¥{{ row.predictedAmount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="recommendedCategory" label="推荐品类" min-width="120" />
        <el-table-column prop="lastPurchase" label="上次购买" min-width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewPredictionDetail(row)">详情</el-button>
            <el-button size="small" type="primary" @click="createMarketingPlan(row)">
              制定营销
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalPredictions"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 预测详情弹窗 -->
    <el-dialog
      v-model="predictionDetailVisible"
      title="购买预测详情"
      width="800px"
      :before-close="handleClosePredictionDetail"
    >
      <PredictionDetailPanel 
        v-if="selectedPrediction"
        :prediction="selectedPrediction"
      />
    </el-dialog>

    <!-- 营销计划弹窗 -->
    <el-dialog
      v-model="marketingPlanVisible"
      title="制定营销计划"
      width="600px"
      :before-close="handleCloseMarketingPlan"
    >
      <MarketingPlanPanel 
        v-if="selectedPrediction"
        :prediction="selectedPrediction"
        @plan-created="handlePlanCreated"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh, MagicStick, Download, ShoppingCart, Money, TrendCharts, Star, Search
} from '@element-plus/icons-vue'
import { LineChart, PieChart as PieChartComponent } from '@/components/charts'

// 导入API
import {
  getPurchaseOverview,
  getPurchaseTimeDistribution,
  getPurchaseAmountDistribution,
  getTopProducts,
  getPurchasePredictions,
  runPurchasePrediction,
  trainPurchaseModel
} from '@/api/prediction'

// 导入子组件
import PredictionDetailPanel from '@/components/prediction/PredictionDetailPanel.vue'
import MarketingPlanPanel from '@/components/prediction/MarketingPlanPanel.vue'

// 响应式数据
const loading = ref(false)
const predicting = ref(false)
const predictionDetailVisible = ref(false)
const marketingPlanVisible = ref(false)
const selectedPrediction = ref(null)

// 筛选和搜索
const searchKeyword = ref('')
const intentFilter = ref('')
const categoryFilter = ref('')
const timeRange = ref('30d')
const amountType = ref('individual')

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const totalPredictions = ref(0)

// 概览数据
const overviewData = reactive({
  highIntentUsers: 2847,
  intentChange: 15.3,
  predictedRevenue: 1250000,
  revenueChange: 22.8,
  avgOrderValue: 439,
  aovChange: 8.5,
  conversionRate: 12.8,
  conversionChange: 3.2
})

// 预测准确性数据
const accuracyData = reactive({
  timeAccuracy: 82.5,
  amountAccuracy: 78.9,
  productAccuracy: 85.2,
  overallAccuracy: 82.2,
  version: 'v1.8.0',
  trainingSamples: 120000,
  lastUpdate: '2024-01-15 16:45:00'
})

// 热门预测产品
const topProducts = ref([
  {
    id: 'P001',
    name: 'iPhone 15 Pro',
    category: '电子产品',
    price: 7999,
    image: '/api/placeholder/60/60',
    predictedSales: 1250,
    probability: 89
  },
  {
    id: 'P002',
    name: '羽绒服外套',
    category: '服装',
    price: 599,
    image: '/api/placeholder/60/60',
    predictedSales: 890,
    probability: 76
  },
  {
    id: 'P003',
    name: '智能手表',
    category: '电子产品',
    price: 2299,
    image: '/api/placeholder/60/60',
    predictedSales: 650,
    probability: 82
  },
  {
    id: 'P004',
    name: '护肤套装',
    category: '美妆',
    price: 299,
    image: '/api/placeholder/60/60',
    predictedSales: 1100,
    probability: 71
  }
])

// 购买时间预测数据
const purchaseTimeLabels = ref(['今天', '明天', '3天内', '1周内', '2周内', '1月内', '3月内'])

const purchaseTimeChartData = ref([
  {
    name: '高意向用户',
    data: [120, 180, 250, 320, 280, 200, 150]
  },
  {
    name: '中意向用户',
    data: [80, 120, 180, 240, 220, 180, 120]
  },
  {
    name: '低意向用户',
    data: [20, 30, 50, 80, 90, 100, 110]
  }
])

// 购买金额预测数据
const purchaseAmountData = ref([
  { name: '0-100元', value: 1250, color: '#91CC75' },
  { name: '100-500元', value: 2890, color: '#FAC858' },
  { name: '500-1000元', value: 1650, color: '#EE6666' },
  { name: '1000-5000元', value: 980, color: '#73C0DE' },
  { name: '5000元以上', value: 320, color: '#3BA272' }
])

// 用户购买预测列表
const purchasePredictions = ref([
  {
    userId: 'U001234',
    userName: '张三',
    purchaseProbability: 0.89,
    intentLevel: 'High',
    predictedDate: '2024-01-18',
    predictedAmount: 1299,
    recommendedCategory: '电子产品',
    lastPurchase: '2023-12-15'
  },
  {
    userId: 'U001235',
    userName: '李四',
    purchaseProbability: 0.76,
    intentLevel: 'High',
    predictedDate: '2024-01-20',
    predictedAmount: 599,
    recommendedCategory: '服装',
    lastPurchase: '2023-12-20'
  },
  {
    userId: 'U001236',
    userName: '王五',
    purchaseProbability: 0.65,
    intentLevel: 'Medium',
    predictedDate: '2024-01-25',
    predictedAmount: 899,
    recommendedCategory: '家居',
    lastPurchase: '2023-12-10'
  },
  {
    userId: 'U001237',
    userName: '赵六',
    purchaseProbability: 0.58,
    intentLevel: 'Medium',
    predictedDate: '2024-01-28',
    predictedAmount: 299,
    recommendedCategory: '美妆',
    lastPurchase: '2023-12-25'
  },
  {
    userId: 'U001238',
    userName: '钱七',
    purchaseProbability: 0.32,
    intentLevel: 'Low',
    predictedDate: '2024-02-05',
    predictedAmount: 199,
    recommendedCategory: '服装',
    lastPurchase: '2023-11-30'
  }
])

// 图表配置（如果需要的话可以保留，但目前ECharts组件会自动处理）

// 计算属性
const filteredPredictions = computed(() => {
  let filtered = purchasePredictions.value

  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(prediction =>
      prediction.userId.toLowerCase().includes(keyword) ||
      prediction.userName.toLowerCase().includes(keyword)
    )
  }

  // 购买意向过滤
  if (intentFilter.value) {
    filtered = filtered.filter(prediction => prediction.intentLevel === intentFilter.value)
  }

  // 产品类别过滤
  if (categoryFilter.value) {
    filtered = filtered.filter(prediction => {
      const categoryMap = {
        'electronics': '电子产品',
        'clothing': '服装',
        'home': '家居',
        'beauty': '美妆'
      }
      return prediction.recommendedCategory === categoryMap[categoryFilter.value]
    })
  }

  return filtered
})

// 方法
const refreshData = async (showMessage = false) => {
  loading.value = true
  try {
    // 并行加载所有数据
    await Promise.all([
      loadOverviewData(),
      loadTimeDistribution(),
      loadAmountDistribution(),
      loadTopProducts(),
      loadPredictions()
    ])

    if (showMessage) {
      ElMessage.success('数据刷新成功')
    }
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('数据刷新失败')
  } finally {
    loading.value = false
  }
}

// 加载概览数据
const loadOverviewData = async () => {
  try {
    const response = await getPurchaseOverview()
    if (response.success && response.data) {
      // 安全地更新概览数据
      const overview = response.data.overview || {}
      overviewData.highIntentUsers = overview.highIntentUsers || 0
      overviewData.intentChange = overview.intentChange || 0
      overviewData.predictedRevenue = overview.predictedRevenue || 0
      overviewData.revenueChange = overview.revenueChange || 0
      overviewData.avgOrderValue = overview.avgOrderValue || 0
      overviewData.aovChange = overview.aovChange || 0
      overviewData.conversionRate = overview.conversionRate || 0
      overviewData.conversionChange = overview.conversionChange || 0

      // 安全地更新准确性数据
      const accuracy = response.data.accuracy || {}
      Object.assign(accuracyData, {
        timeAccuracy: accuracy.timeAccuracy || accuracyData.timeAccuracy,
        amountAccuracy: accuracy.amountAccuracy || accuracyData.amountAccuracy,
        productAccuracy: accuracy.productAccuracy || accuracyData.productAccuracy,
        overallAccuracy: accuracy.overallAccuracy || accuracyData.overallAccuracy,
        version: accuracy.version || accuracyData.version,
        trainingSamples: accuracy.trainingSamples || accuracyData.trainingSamples,
        lastUpdate: accuracy.lastUpdate || accuracyData.lastUpdate
      })
    }
  } catch (error) {
    console.error('加载概览数据失败:', error)
  }
}

// 加载时间分布数据
const loadTimeDistribution = async () => {
  try {
    const response = await getPurchaseTimeDistribution({ timeRange: timeRange.value })
    if (response.success && response.data && Array.isArray(response.data)) {
      // 提取日期标签和数据
      purchaseTimeLabels.value = response.data.map(item => item.date || '')

      purchaseTimeChartData.value = [{
        name: '预测购买用户数',
        data: response.data.map(item => item.count || 0),
        color: '#5470c6'
      }]

      console.log('时间分布数据加载成功:', purchaseTimeChartData.value)
    }
  } catch (error) {
    console.error('加载时间分布数据失败:', error)
  }
}

// 加载金额分布数据
const loadAmountDistribution = async () => {
  try {
    const response = await getPurchaseAmountDistribution({ amountType: amountType.value })
    if (response.success && response.data && Array.isArray(response.data)) {
      purchaseAmountData.value = response.data.map(item => ({
        name: item.name || '未知',
        value: item.value || 0,
        color: item.color || '#5f27cd'
      }))

      console.log('金额分布数据加载成功:', purchaseAmountData.value)
    }
  } catch (error) {
    console.error('加载金额分布数据失败:', error)
  }
}

// 加载热门产品数据
const loadTopProducts = async () => {
  try {
    const response = await getTopProducts()
    if (response.success && response.data && Array.isArray(response.data)) {
      topProducts.value = response.data
      console.log('热门产品数据加载成功:', topProducts.value)
    }
  } catch (error) {
    console.error('加载热门产品数据失败:', error)
  }
}

// 加载预测列表数据
const loadPredictions = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      searchKeyword: searchKeyword.value,
      intentFilter: intentFilter.value,
      categoryFilter: categoryFilter.value
    }

    const response = await getPurchasePredictions(params)
    if (response.success && response.data) {
      purchasePredictions.value = response.data.predictions || []
      const pagination = response.data.pagination || {}
      totalPredictions.value = pagination.total_count || 0

      console.log('预测列表数据加载成功:', purchasePredictions.value.length)
    } else {
      purchasePredictions.value = []
      totalPredictions.value = 0
    }
  } catch (error) {
    console.error('加载预测列表数据失败:', error)
    purchasePredictions.value = []
    totalPredictions.value = 0
  }
}

const runPrediction = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要执行购买预测吗？这将为所有活跃用户生成最新的购买意向评估。',
      '确认执行预测',
      { type: 'warning' }
    )

    predicting.value = true

    const response = await runPurchasePrediction()
    if (response.success) {
      ElMessage.success(response.message)
      // 刷新数据
      await refreshData()
    } else {
      ElMessage.error(response.message || '预测执行失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('执行预测失败:', error)
      ElMessage.error('预测执行失败')
    }
  } finally {
    predicting.value = false
  }
}

const exportResults = () => {
  // 导出预测结果
  const data = filteredPredictions.value
  const csvContent = [
    ['用户ID', '用户姓名', '购买概率', '购买意向', '预测购买时间', '预测金额', '推荐品类', '上次购买'],
    ...data.map(prediction => [
      prediction.userId,
      prediction.userName,
      prediction.purchaseProbability,
      prediction.intentLevel,
      prediction.predictedDate,
      prediction.predictedAmount,
      prediction.recommendedCategory,
      prediction.lastPurchase
    ])
  ].map(row => row.join(',')).join('\n')

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `purchase_prediction_${new Date().toISOString().split('T')[0]}.csv`
  link.click()

  ElMessage.success('预测结果已导出')
}

const getIntentColor = (intentLevel) => {
  const colorMap = {
    'high': '#F56C6C',
    'High': '#F56C6C',
    'medium': '#E6A23C',
    'Medium': '#E6A23C',
    'low': '#67C23A',
    'Low': '#67C23A'
  }
  return colorMap[intentLevel] || '#909399'
}

const getIntentTagType = (intentLevel) => {
  const typeMap = {
    'high': 'danger',
    'High': 'danger',
    'medium': 'warning',
    'Medium': 'warning',
    'low': 'success',
    'Low': 'success'
  }
  return typeMap[intentLevel] || 'info'
}

const getIntentLevelText = (intentLevel) => {
  const textMap = {
    'high': '高意向',
    'High': '高意向',
    'medium': '中意向',
    'Medium': '中意向',
    'low': '低意向',
    'Low': '低意向'
  }
  return textMap[intentLevel] || '未知'
}

const viewPredictionDetail = (prediction) => {
  selectedPrediction.value = {
    ...prediction,
    // 添加详细预测数据
    factors: [
      { name: '浏览频率', value: 85, impact: 'high' },
      { name: '购物车行为', value: 72, impact: 'medium' },
      { name: '历史购买', value: 68, impact: 'medium' },
      { name: '价格敏感度', value: 45, impact: 'low' }
    ],
    recommendations: [
      '推送个性化产品推荐',
      '发送限时优惠券',
      '展示相关产品评价',
      '提供分期付款选项'
    ]
  }
  predictionDetailVisible.value = true
}

const createMarketingPlan = (prediction) => {
  selectedPrediction.value = prediction
  marketingPlanVisible.value = true
}

const handleClosePredictionDetail = () => {
  predictionDetailVisible.value = false
  selectedPrediction.value = null
}

const handleCloseMarketingPlan = () => {
  marketingPlanVisible.value = false
  selectedPrediction.value = null
}

const handlePlanCreated = (plan) => {
  ElMessage.success('营销计划创建成功')
  marketingPlanVisible.value = false
}

const handleSortChange = ({ column, prop, order }) => {
  // 实现排序逻辑
  console.log('排序变化:', { column, prop, order })
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 监听器
watch([timeRange], () => {
  // 时间范围变化时重新加载时间分布数据
  loadTimeDistribution()
})

watch([amountType], () => {
  // 金额类型变化时重新加载金额分布数据
  loadAmountDistribution()
})

watch([searchKeyword, intentFilter, categoryFilter, currentPage, pageSize], () => {
  // 搜索和筛选条件变化时重新加载预测列表
  loadPredictions()
})



// 生命周期
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.purchase-prediction-page {
  padding: 0;
  background-color: transparent;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 概览统计 */
.overview-section {
  margin-bottom: 24px;
}

.metric-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
  height: 120px;
}

.metric-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.metric-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.metric-card.purchase-intent .metric-icon {
  background: linear-gradient(135deg, #67bb6a, #4caf50);
}

.metric-card.predicted-revenue .metric-icon {
  background: linear-gradient(135deg, #42a5f5, #2196f3);
}

.metric-card.avg-order-value .metric-icon {
  background: linear-gradient(135deg, #ffa726, #ff9800);
}

.metric-card.conversion-rate .metric-icon {
  background: linear-gradient(135deg, #ab47bc, #9c27b0);
}

.metric-content {
  flex: 1;
}

.metric-content h3 {
  margin: 0 0 4px 0;
  font-size: 28px;
  font-weight: 700;
  color: #333;
}

.metric-content p {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.metric-change {
  font-size: 12px;
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 12px;
}

.metric-change.success {
  background: #f0f9ff;
  color: #10b981;
}

.metric-change.warning {
  background: #fffbeb;
  color: #f59e0b;
}

/* 卡片样式 */
.chart-card,
.product-recommendation-card,
.accuracy-card,
.prediction-list-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
}

.chart-card :deep(.el-card__header),
.product-recommendation-card :deep(.el-card__header),
.accuracy-card :deep(.el-card__header),
.prediction-list-card :deep(.el-card__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 图表容器 */
.chart-container {
  padding: 20px;
  height: 400px;
}

/* 购买金额预测分布卡片特殊样式 */
.chart-card:nth-of-type(2) {
  min-height: 500px;
}

/* 右侧卡片高度调整 */
.product-recommendation-card {
  min-height: 280px;
}

.accuracy-card {
  min-height: 400px;
}

/* 产品推荐 */
.product-list {
  padding: 20px 0;
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.product-image {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  object-fit: cover;
}

.product-details h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.product-category {
  margin: 0 0 4px 0;
  font-size: 12px;
  color: #666;
}

.product-price {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #f56c6c;
}

.product-metrics {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 120px;
}

.metric {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.metric .label {
  font-size: 12px;
  color: #666;
}

.metric .value {
  font-size: 12px;
  font-weight: 600;
  color: #333;
}

/* 准确性分析 */
.accuracy-metrics {
  padding: 20px 0;
}

.accuracy-item {
  margin-bottom: 20px;
}

.accuracy-item:last-child {
  margin-bottom: 0;
}

.accuracy-label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.accuracy-value {
  display: flex;
  align-items: center;
  gap: 12px;
}

.accuracy-value .el-progress {
  flex: 1;
}

.percentage {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  min-width: 45px;
}

.model-info {
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
  margin-top: 20px;
}

.model-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #666;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  border-top: 1px solid #f0f0f0;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .header-actions {
    justify-content: center;
    flex-wrap: wrap;
  }

  .metric-card {
    height: auto;
    min-height: 100px;
  }

  .product-item {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .product-metrics {
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
}
</style>
